import sys
import os

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from models import AsyncSessionFactory
from models.seckill import Commodity, Seckill
from datetime import datetime, timedelta
import asyncio
from decimal import Decimal
from sqlalchemy import text


async def init_seckill_data():
    """初始化秒杀测试数据"""
    
    # 商品1: iPhone 15 Pro Max
    commodity1 = Commodity(
        title="Apple iPhone 15 Pro Max 512GB 钛原色",
        covers=[
            'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-1a_AVIF?wid=750&hei=750&fmt=jpeg&qlt=95&.v=1693086369952',
            'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-2_AVIF?wid=750&hei=750&fmt=jpeg&qlt=95&.v=1693086369327',
            'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-3_AVIF?wid=750&hei=750&fmt=jpeg&qlt=95&.v=1693086370424'
        ],
        price=Decimal('12999.00'),
        detail='''
        <div class="product-detail">
            <h3>产品特点</h3>
            <ul>
                <li>6.7英寸超视网膜XDR显示屏</li>
                <li>A17 Pro仿生芯片</li>
                <li>专业级摄像头系统</li>
                <li>钛金属设计，坚固轻盈</li>
                <li>支持MagSafe无线充电</li>
            </ul>
            <img src="https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-max-naturaltitanium-pdp-image-position-1a_AVIF?wid=750&hei=750&fmt=jpeg&qlt=95&.v=1693086369952" alt="iPhone 15 Pro Max" style="width:100%;max-width:500px;">
        </div>
        '''
    )
    
    # 商品2: MacBook Pro
    commodity2 = Commodity(
        title="MacBook Pro 14英寸 M3 芯片 512GB SSD 深空灰色",
        covers=[
            'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/mbp14-spacegray-select-202310_GEO_CN?wid=904&hei=840&fmt=jpeg&qlt=90&.v=1697311054290',
            'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/mbp14-spacegray-cto-hero-202310_GEO_CN?wid=904&hei=840&fmt=jpeg&qlt=90&.v=1697311632097'
        ],
        price=Decimal('15999.00'),
        detail='''
        <div class="product-detail">
            <h3>产品亮点</h3>
            <ul>
                <li>14.2英寸Liquid Retina XDR显示屏</li>
                <li>M3芯片，8核CPU和10核GPU</li>
                <li>512GB SSD存储</li>
                <li>16GB统一内存</li>
                <li>专业级视频剪辑性能</li>
            </ul>
            <img src="https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/mbp14-spacegray-select-202310_GEO_CN?wid=904&hei=840&fmt=jpeg&qlt=90&.v=1697311054290" alt="MacBook Pro" style="width:100%;max-width:500px;">
        </div>
        '''
    )
    
    # 商品3: AirPods Pro
    commodity3 = Commodity(
        title="AirPods Pro (第二代) USB-C充电盒",
        covers=[
            'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MQD83_AV2?wid=750&hei=750&fmt=jpeg&qlt=95&.v=1660803972361',
            'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MQD83_AV3?wid=750&hei=750&fmt=jpeg&qlt=95&.v=1660803972315'
        ],
        price=Decimal('1899.00'),
        detail='''
        <div class="product-detail">
            <h3>产品特色</h3>
            <ul>
                <li>主动降噪技术</li>
                <li>通透模式</li>
                <li>个性化空间音频</li>
                <li>MagSafe充电盒</li>
                <li>最长可达6小时聆听时间</li>
            </ul>
            <img src="https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/MQD83_AV2?wid=750&hei=750&fmt=jpeg&qlt=95&.v=1660803972361" alt="AirPods Pro" style="width:100%;max-width:500px;">
        </div>
        '''
    )
    
    # 商品4: 小米14 Ultra
    commodity4 = Commodity(
        title="小米14 Ultra 16GB+512GB 钛金属特别版",
        covers=[
            'https://cdn.cnbj0.fds.api.mi-img.com/b2c-shopapi-pms/pms_1708073767.41850073.jpg',
            'https://cdn.cnbj0.fds.api.mi-img.com/b2c-shopapi-pms/pms_1708073767.81469588.jpg'
        ],
        price=Decimal('6499.00'),
        detail='''
        <div class="product-detail">
            <h3>产品亮点</h3>
            <ul>
                <li>6.73英寸C8发光材料屏幕</li>
                <li>徕卡影像系统</li>
                <li>骁龙8 Gen 3处理器</li>
                <li>5300mAh大电池</li>
                <li>90W有线+80W无线充电</li>
            </ul>
            <img src="https://cdn.cnbj0.fds.api.mi-img.com/b2c-shopapi-pms/pms_1708073767.41850073.jpg" alt="小米14 Ultra" style="width:100%;max-width:500px;">
        </div>
        '''
    )
    
    # 商品5: 华为MateBook X Pro
    commodity5 = Commodity(
        title="华为MateBook X Pro 2024款 i7 32GB+1TB 星际蓝",
        covers=[
            'https://res.vmallres.com/20240220/c72fd83b0c8b4d8aa9d7b3c1f5e90e7e.jpg',
            'https://res.vmallres.com/20240220/8a5d7f4e9c2b4a3bb6e8d1c0f7a9e2b3.jpg'
        ],
        price=Decimal('11999.00'),
        detail='''
        <div class="product-detail">
            <h3>产品特色</h3>
            <ul>
                <li>14.2英寸3.1K触控屏</li>
                <li>Intel Core i7-13700H处理器</li>
                <li>32GB LPDDR5内存</li>
                <li>1TB PCIe SSD</li>
                <li>超级终端多屏协同</li>
            </ul>
            <img src="https://res.vmallres.com/20240220/c72fd83b0c8b4d8aa9d7b3c1f5e90e7e.jpg" alt="华为MateBook X Pro" style="width:100%;max-width:500px;">
        </div>
        '''
    )
    
    # 创建秒杀活动
    now = datetime.now()
    
    # 批量插入数据
    async with AsyncSessionFactory() as session:
        async with session.begin():
            # 首先添加商品
            session.add_all([commodity1, commodity2, commodity3, commodity4, commodity5])
            # 刷新以获取商品ID
            await session.flush()
            
            # 创建秒杀活动（使用商品ID）
            # 秒杀1: iPhone 限时抢购 (正在进行)
            seckill1 = Seckill(
                commondity_id=commodity1.id,
                start_time=now - timedelta(hours=2),
                end_time=now + timedelta(hours=22),
                max_sk_count=50,
                sk_per_max_count=2,
                sk_price=Decimal('9999.00'),
                stock=10,
            )
            
            # 秒杀2: MacBook Pro 明日开抢 (即将开始)
            seckill2 = Seckill(
                commondity_id=commodity2.id,
                start_time=now + timedelta(hours=12),
                end_time=now + timedelta(hours=36),
                max_sk_count=20,
                sk_per_max_count=1,
                sk_price=Decimal('1299.00'),
                stock=20,
            )
            
            # 秒杀3: AirPods Pro 每日特价 (正在进行)
            seckill3 = Seckill(
                commondity_id=commodity3.id,
                start_time=now - timedelta(hours=6),
                end_time=now + timedelta(hours=18),
                max_sk_count=100,
                sk_per_max_count=5,
                sk_price=Decimal('1299.00'),
                stock=50
            )
            
            # 秒杀4: 小米14 Ultra 周末特惠 (即将开始)
            seckill4 = Seckill(
                commondity_id=commodity4.id,
                start_time=now + timedelta(days=1),
                end_time=now + timedelta(days=3),
                max_sk_count=30,
                sk_per_max_count=2,
                sk_price=Decimal('5999.00'),
                stock=50
            )
            
            # 秒杀5: 华为MateBook 限时抢购 (已结束)
            seckill5 = Seckill(
                commondity_id=commodity5.id,
                start_time=now - timedelta(days=2),
                end_time=now - timedelta(hours=6),
                max_sk_count=15,
                sk_per_max_count=1,
                sk_price=Decimal('9999.00'),
                stock=2
            )
            
            # 添加秒杀活动
            session.add_all([seckill1, seckill2, seckill3, seckill4, seckill5])
            
        print('✅ 秒杀测试数据添加成功！')
        print(f'📦 添加了 5 个商品')
        print(f'⚡ 添加了 5 个秒杀活动')
        print(f'🔥 其中 2 个正在进行，2 个即将开始，1 个已结束')


async def clear_seckill_data():
    """清除所有秒杀测试数据"""
    async with AsyncSessionFactory() as session:
        async with session.begin():
            # 先删除秒杀记录（因为有外键依赖）
            await session.execute(text("DELETE FROM seckill"))
            # 再删除商品记录
            await session.execute(text("DELETE FROM commodity"))
            
        print('🧹 所有秒杀测试数据已清除')


if __name__ == "__main__":
    import sys
    
    if len(sys.argv) > 1 and sys.argv[1] == "clear":
        asyncio.run(clear_seckill_data())
    else:
        asyncio.run(init_seckill_data())
